package mh.message;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.logging.Logger;

/**
 * This class analyze INcoming string from server and convert them to <code>IncomingMessage</code> format. Messages are
 * parsed.<br>
 * The <code>parseMessage(String message)</code> method is <code>STATIC</code>.
 * 
 * @author Gianmarco Laggia
 * 
 */
public class MessageParser {

	private static IncomingMessage	msg;
	/**
	 * The logger
	 */
	private static final Logger		LOG	= Logger.getLogger(MessageParser.class.getName());

	/**
	 * Creates a new <code>IncomingMessage</code> separating each part of the message in different string, as asked by
	 * the object.<br>
	 * This method follows the RCF1459 - Internet Relay Chat protocol.
	 * 
	 * @param incMsg
	 *            A string incoming from the socket, has to be IRC protocol valid.
	 * @return <code>IncomingMessage</code> formatted message.
	 * @throws ParseException
	 *             In case <code>incMsg</code> is not a valid IRC message.
	 */
	public static IncomingMessage parseMessage(String incMsg) throws ParseException {

		msg = new IncomingMessage();

		if (incMsg == null) {
			// ************ LOG ************ //
			LOG.severe("Received a null string.");
			// ***************************** //
			throw new ParseException("Null String", 0);
		}

		StringTokenizer st = new StringTokenizer(incMsg, " ");
		String t;

		if (!st.hasMoreTokens()) {
			// ************ LOG ************ //
			LOG.severe("Received an empty message.");
			// ***************************** //
			throw new ParseException("empty message", 0);
		}
		t = st.nextToken();

		/*
		 * control if there's a prefix
		 */
		if (t.charAt(0) == ':') {
			if (t.length() == 1) {
				// ************ LOG ************ //
				LOG.warning("Received a message with empty prefix");
				// ***************************** //
				throw new ParseException("empty prefix", 1);
			}

			msg.setPrefix(t.substring(1));
			parsePrefix(t.substring(1));

			if (!st.hasMoreTokens()) {
				// ************ LOG ************ //
				LOG.warning("Received a message without command.");
				// ***************************** //
				throw new ParseException("command expected", 0);
			} else {
				t = st.nextToken();
			}
		} else {
			msg.setPrefix("");
		}

		/*
		 * here we expect to have command string. If we've not any param and message needs more than 0 params,
		 * exception.
		 */
		msg.setCommand(t);
		if (!st.hasMoreTokens() && (MessageValidator.getRequiredParams(t) > 0)) {
			// ************ LOG ************ //
			LOG.warning("More parameters expected.");
			// ***************************** //
			throw new ParseException("parameters expected", 0);
		}

		ArrayList<String> par = new ArrayList<String>();
		/*
		 * analyze parameters if they're present
		 */
		if (st.hasMoreTokens()) {
			st = new StringTokenizer(st.nextToken(""), " ");
			while (st.hasMoreTokens()) {
				t = st.nextToken();
				if (t.charAt(0) == ':') {
					/*
					 * Last param, afer ":" we can find more token special case, managed after...
					 */
					break;
				}
				par.add(t);
			}

			/*
			 * last param made of all token after second ":"
			 */
			int colon_index = incMsg.indexOf(':', 1);
			if (-1 != colon_index) {
				par.add(incMsg.substring(colon_index + 1));
			}
		}

		msg.setParams(par);

		MessageValidator.isAcceptable(msg);

		return msg;
	}

	//}

	public static void parsePrefix(String prefix) {

		String[] str = prefix.split("!");

		if (str.length > 1) {
			//nick!user@host
			msg.setNick(str[0]);
			String[] str2 = str[1].split("@");
			msg.setUser(str2[0]);
			msg.setHost(str2[1]);
		} else {

			msg.setNick(prefix);

		}

	}
}
